<template>
    <rui-page :defines="defines">
        <rui-query :label-width="200"
                   ref="searchForm"
                   :query="queryData"
                   :query-rows="searchFormOptions"
        />
        <rui-table
            :defineId="'voucherEvnetsDifine'"
            :fixedLeft="['action']"
            :showIndex="false"
            :select="false"
            :columns="eventsColumns"
            :slots="[{key:'action',slot:'action'}]"
            @loadDatas="queryData"
            ref-query="searchForm"
            ref="eventsTable"
        >
            <template slot="toolBar">
                <Button @click="add" icon="md-add" type="primary">新增</Button>
            </template>
            <template slot="action" slot-scope="{ row }">
                <div>
                    <Button @click="edit(row)" size="small" type="primary" v-if="row.status!='active'">编辑</Button>
                    <Button @click="active(row)" size="small" type="success" v-if="row.status!='active'">生效</Button>
                    <Button @click="invalidity(row)" size="small"  type="error" v-if="row.status=='active'">无效
                    </Button>
                    <Button @click="view(row)" size="small" type="primary">查看</Button>
                    <Button type="error" size="small" @click="remove(row)" v-if="row.status!='active'">删除</Button>
                    <circleLoading v-if="operationLoading"/>
                </div>
            </template>
        </rui-table>
        <Modal v-model="isShowModel" :title="modelTitle" :width="800" :closable="false"
               :mask-closable="false" @on-ok="eventsSubmit">
            <Form ref="eventsForm" :model="eventsForm"  :label-width="120" :rules="vouchereventsValidate">
                <Row :gutter="32">
                    <Col span="12" >
                        <FormItem label="主业务事件代码" prop="mainBusinessCode" :required=true>
                            <Poptip v-model="visibleMain" placement="right-start" title="选择主业务事件代码">
                                <Input v-model="eventsForm.mainBusinessCode"
                                       :clearable="status!='view'"
                                       readonly
                                       :disabled="status=='view'"
                                       :style="{width:(item.width?item.width:200)+'px'}"/>
                                <div slot="content">
                                    <Input v-model="searchMainKey" suffix="ios-search" @on-change="remoteMain"
                                           placeholder="输入主业务事件代码搜索"/>
                                    <Scroll :on-reach-bottom="handleReachMainBottom">
                                        <Dropdown @on-click="scollListMainClick">
                                            <DropdownMenu>
                                                <DropdownItem :name="item.mainBusinessCode" v-for="item in options1">{{
                                                    item.mainBusinessCode+":"+ item.mainBusiness}}
                                                </DropdownItem>
                                            </DropdownMenu>
                                        </Dropdown>
                                    </Scroll>
                                </div>
                            </Poptip>
                        </FormItem>
                    </Col>
                    <Col span="12" >
                            <FormItem label="主业务事件名称" prop="mainBusiness"  >
                                <Input v-model="eventsForm.mainBusiness"
                                       readonly
                                       :disabled="status=='view'"
                                       :style="{width:(item.width?item.width:100)+'%'}"/>
                            </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="12" >
                        <FormItem label="子业务事件代码" prop="childBusinessCode" :required=true>
                            <Poptip v-model="visibleChild" placement="right-start" title="选择子业务事件代码" >
                                <Input v-model="eventsForm.childBusinessCode"
                                       :clearable="status!='view'"
                                       readonly
                                       :disabled="status=='view'"
                                       :style="{width:(item.width?item.width:200)+'px'}"/>
                                <div slot="content">
                                    <Input v-model="searchChildKey" suffix="ios-search" @on-change="remoteChild"
                                           placeholder="输入子业务事件代码搜索"/>
                                    <Scroll :on-reach-bottom="handleReachChildBottom">
                                        <Dropdown @on-click="scollListChldClick">
                                            <DropdownMenu>
                                                <DropdownItem :name="item.childBusinessCode" v-for="item in options2">{{
                                                    item.childBusinessCode+":"+ item.childBusiness}}
                                                </DropdownItem>
                                            </DropdownMenu>
                                        </Dropdown>
                                    </Scroll>
                                </div>
                            </Poptip>
                        </FormItem>
                    </Col>
                    <Col span="12" >
                        <FormItem label="子业务事件名称" prop="childBusiness"  >
                            <Input v-model="eventsForm.childBusiness"
                                   readonly
                                   :disabled="status=='view'"
                                   :style="{width:(item.width?item.width:100)+'%'}"/>
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col  span="12">
                        <FormItem label="埋点编号" prop="buriedPointNo" :required=true>
                            <Poptip v-model="visibleBuriedPoint" placement="right-start" title="选择埋点编号" >
                                <Input v-model="eventsForm.buriedPointNo"
                                       :clearable="status!='view'"
                                       readonly
                                       :disabled="status=='view'"
                                       :style="{width:(item.width?item.width:200)+'px'}"/>
                                <div slot="content">
                                    <Input v-model="searchBuriedPointKey" suffix="ios-search" @on-change="remoteBuriedPoint"
                                           placeholder="输入埋点编号搜索"/>
                                    <Scroll :on-reach-bottom="handleReachBuriedPointBottom">
                                        <Dropdown @on-click="scollListBuriedPointClick">
                                            <DropdownMenu>
                                                <DropdownItem :name="item.buriedPointNo" v-for="item in options3">{{
                                                    item.buriedPointNo+":"+ item.buriedPointName}}
                                                </DropdownItem>
                                            </DropdownMenu>
                                        </Dropdown>
                                    </Scroll>
                                </div>
                            </Poptip>
                        </FormItem>
                    </Col>
                    <Col span="12" >
                        <FormItem label="埋点名称" prop="buriedPointName"  >
                            <Input v-model="eventsForm.buriedPointName"
                                   readonly
                                   :disabled="status=='view'"
                                   :style="{width:(item.width?item.width:100)+'%'}"/>
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="描述" prop="description" :required=true>
                            <Input v-model="eventsForm.description" type="textarea"
                                   :style="{width:(item.width?item.width:400)+'px'}"
                                   :disabled="status=='view'"/>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button size="small" @click="isShowModel = false">取消</Button>
                <Button type="primary" size="small" :loading="submitLoading" @click="eventsSubmit"
                        v-show="status!='view'">保存
                </Button>
            </div>
        </Modal>
    </rui-page>
</template>
<script>
    import voucherEvnetsDifine from "../defines/voucher-events-define";
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import {
        getVoucherEventsList,
        delVoucherEvents,
        addVoucherEvents,
        modifyVoucherEvents,
        active,
        invalidity
    } from "@/projects/basic/api/contract/voucher/voucherEvents";
    import {
        listVoucher
    } from "@/projects/basic/api/contract/voucher/voucherTemplate";
    import {
        list
    } from "@/projects/basic/api/contract/voucher/voucherBuryingPoint";

    export default {
        name: "product-atom",
        components: {
            circleLoading
        },
        data() {
            return {
                operationLoading: false,
                submitLoading: false,
                isShowModel: false,
                modelTitle: null,
                searchFormOptions: [
                    {
                        defineId: "voucherEvnetsDifine",
                        span: 6,
                        fields: ["mainBusinessCode", "childBusinessCode", "buriedPointNo", 'status']
                    },
                ],
                eventsColumns: [
                    'action','buriedPointName', 'buriedPointNo', 'mainBusiness','mainBusinessCode', 'childBusiness', 'childBusinessCode', 'description', 'status', 'createBy', 'createTime', 'updateBy', 'updateTime'
                ],
                status: null,
                options1: [],
                list1: [],
                visibleMain: false,
                visibleChild: false,
                options2: [],
                list2: [],
                options3: [],
                list3: [],
                visibleBuriedPoint:false,
                selectFrom: {
                    condition: {
                        businessType: null,
                        businessCode: null,
                    },
                    pageNumber: 1,
                    pageSize: 10
                },
                vouchereventsValidate: {
                    mainBusinessCode: [
                        {required: true, message: "主业务事件代码不能为空", trigger: "change"},
                    ],
                    childBusinessCode: [
                        {required: true, message: "子业务事件代码不能为空", trigger: "change"},
                    ],
                    buriedPointNo: [
                        {required: true, message: "埋点编号不能为空", trigger: "change"},
                    ],
                    description: [
                        {required: true, message: "描述不能为空", trigger: "change"},
                    ],
                },
                eventsForm: {
                    buriedPointNo: null,
                    mainBusinessCode: null,
                    childBusinessCode: null,
                    description: null
                },
                item: {
                    with: 200,
                },
                searchMainKey: "",
                searchChildKey: "",
                searchBuriedPointKey: "",
            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "voucherEvnetsDifine",
                        fields: voucherEvnetsDifine
                    }
                ];
            }
        },
        methods: {
            queryData(queryData) {
                console.log(queryData);
                getVoucherEventsList(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.eventsTable.updateTableData(records, total);
                    }
                });
            },
            refresh() {
                this.$refs['eventsTable'].reloadData();
            },
            add() {
                this.modalType = 0;
                this.modalTitle = "新增";
                this.isShowModel = true;
                this.status = "new";
                this.$nextTick(() => {
                    this.$refs.eventsForm.resetFields();
                })
            },
            edit(row) {
                this.modalType = 1;
                this.modalTitle = "编辑";
                this.status = "edit";
                this.eventsForm = deepClone(row);
                this.isShowModel = true;
            },
            view(row) {
                this.modalTitle = "查看";
                this.eventsForm = deepClone(row);
                this.status = "view";
                this.isShowModel = true;
            },
            eventsSubmit() {
                this.$refs.eventsForm.validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            this.submitLoading = true;
                            addVoucherEvents(this.eventsForm)
                                .then(res => {
                                    this.submitLoading = false;
                                    if (res.code === "0000") {
                                        this.$Message.success("操作成功");
                                        this.isShowModel = false;
                                        this.refresh();
                                    }
                                }).catch(() => {
                                this.submitLoading = false;
                            });

                        } else {
                            // 编辑
                            this.submitLoading = true;
                            modifyVoucherEvents(this.eventsForm)
                                .then(res => {
                                    this.submitLoading = false;
                                    if (res.code === "0000") {
                                        this.$Message.success("操作成功");
                                        this.isShowModel = false;
                                        this.refresh();
                                    }
                                }).catch(() => {
                                this.submitLoading = false;
                            });
                        }
                    }
                });
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除子业务事件: " + v.childBusinessCode + " ?",
                    onOk: () => {
                        this.operationLoading = true;
                        delVoucherEvents(v.id).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("删除成功");
                                this.refresh();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
            //设置无效
            invalidity(v) {
                this.$Modal.confirm({
                    title: "设置无效",
                    content: "您确认要设置成无效?",
                    onOk: () => {
                        this.operationLoading = true;
                        invalidity(v.id).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("无效成功");
                                this.refresh();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
            //设置生效
            active(v) {
                this.$Modal.confirm({
                    title: "设置生效",
                    content: "您确认要设置成生效?",
                    onOk: () => {
                        this.operationLoading = true;
                        active(v.id).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("生效成功");
                                this.refresh();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },

            //加载页面数据
            loadForm() {
                this.remoteMethod();
                this.remoteMethodBuriedPoint();
            },
            //查询事件代码
            remoteMethod() {
                listVoucher()
                    .then(res => {
                        if (res.code === "0000") {
                            var  val  =null;
                            res.data.forEach(e=>   {
                                if(val!=e.mainBusinessCode){
                                    this.list1.push(e)
                                    val=e.mainBusinessCode;
                                }
                            });
                            this.options1 = this.list1;
                            this.list2 = res.data;
                            this.options2 = this.list2;
                        }
                    }).catch(() => {
                    this.list1 = [];
                    this.options1 = [];
                    this.list2 = [];
                    this.options2 = [];
                });
            },

            //查询埋点编号
            remoteMethodBuriedPoint() {
                list(this.selectFrom, "contractAccount")
                        .then(res => {
                            if (res.code === "0000") {
                                this.list3 = res.data;
                                this.options3 = this.list3 ;
                            }
                        }).catch(() => {
                        this.list3 = [];
                        this.options3 = [];
                    });
            },
            handleReachMainBottom() {
                return new Promise(resolve => {
                    setTimeout(() => {
                        const last = this.options1[this.options1.length - 1];
                        for (let i = 1; i < 11; i++) {
                            this.options1.push(last + i);
                        }
                        resolve();
                    }, 2000);
                });
            },
            remoteMain() {
                this.options1 = [];
                for (var i = 0; i < this.list1.length; i++) {
                    if (this.list1[i].mainBusinessCode.indexOf(this.searchMainKey) > -1) {
                        this.options1.push(this.list1[i])
                    }
                }
            },
            // 主事件赋值
            scollListMainClick(val) {
                this.options1.forEach(c => {
                    if (c.mainBusinessCode == val) {
                        this.eventsForm.mainBusinessCode = c.mainBusinessCode;
                        this.eventsForm.mainBusiness = c.mainBusiness;
                        this.eventsForm.childBusinessCode = "";
                        this.eventsForm.childBusiness = "";
                        this.visibleMain = false;
                    }
                })
                this.options2 = [];
                for (var i = 0; i < this.list2.length; i++) {
                    if (this.list2[i].mainBusinessCode == this.eventsForm.mainBusinessCode) {
                        this.options2.push(this.list2[i])
                    }
                }
            },
            //  子事件赋值
            scollListChldClick(val) {
                this.options2.forEach(c => {
                    if (c.childBusinessCode == val) {
                        this.eventsForm.childBusinessCode = c.childBusinessCode;
                        this.eventsForm.childBusiness = c.childBusiness;
                        this.visibleChild = false;
                    }
                })
            },
            //查询子事件代码
            handleReachChildBottom() {
                return new Promise(resolve => {
                    setTimeout(() => {
                        const last = this.options2[this.options2.length - 1];
                        for (let i = 1; i < 11; i++) {
                            this.options2.push(last + i);
                        }
                        resolve();
                    }, 2000);
                });
            },
            remoteChild() {
                this.options2 = [];
                for (var i = 0; i < this.list2.length; i++) {
                    if (this.list2[i].childBusinessCode.indexOf(this.searchChildKey) > -1 && this.list2[i].mainBusinessCode == this.eventsForm.mainBusinessCode) {
                        this.options2.push(this.list2[i])
                    }
                }
            },

            //  埋点赋值
            scollListBuriedPointClick(val) {
                this.options3.forEach(c => {
                    if (c.buriedPointNo == val) {
                        this.eventsForm.buriedPointNo = c.buriedPointNo;
                        this.eventsForm.buriedPointName = c.buriedPointName;
                        this.visibleBuriedPoint = false;
                    }
                })
            },
            //查询埋点代码
            handleReachBuriedPointBottom() {
                return new Promise(resolve => {
                    setTimeout(() => {
                        const last = this.options3[this.options3.length - 1];
                        for (let i = 1; i < 11; i++) {
                            this.options3.push(last + i);
                        }
                        resolve();
                    }, 2000);
                });
            },
            remoteBuriedPoint() {
                this.options3 = [];
                for (var i = 0; i < this.list3.length; i++) {
                    if (this.list3[i].buriedPointNo.indexOf(this.searchBuriedPointKey) > -1) {
                        this.options3.push(this.list3[i])
                    }
                }
            },
        },
        mounted() {
            this.loadForm();
            this.refresh();
        }
    };
</script>
